package cn.pud.rpademo01;

/**
 * @Author: Miyako
 * @Date: 2024-11-11-17:32
 * @Description:
 */
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmailDemo {
    public static void main(String[] args) throws Exception {
        // SMTP 服务器配置
        String host = "smtp.163.com";
        String port = "25"; // smtp服务端口号
        String username = "miyakonano@163.com";
        String password = "";

        // 收件人和邮件内容
        String to = "@qq.com"; // 收件人地址
//        String to = "@qq.com"; // 收件人地址
        String subject = "No Yes Brother";
        String bodyText = "Bsgm";

        // 设置邮件的属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true"); // 启用 STARTTLS（安全连接）

        // 获取邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // 创建邮件消息
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));  // 发件人
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人
        message.setSubject(subject);  // 邮件主题
        message.setText(bodyText);  // 邮件正文


        // 创建 MimeMultipart 对象
        MimeMultipart multipart = new MimeMultipart("related");

        // 创建 HTML 邮件部分
        MimeBodyPart htmlPart = new MimeBodyPart();
        String htmlContent = "<html><body>" +
                "<h1>不是革门</h1>" +
                "<p>不是哥们？？？？？？？？？</p>" +
                "<img src='cid:image1'>" + // 引用 Content-ID
                "</body></html>";
        htmlPart.setContent(htmlContent, "text/html;charset=UTF-8");

        // 创建图片部分
        MimeBodyPart imagePart = new MimeBodyPart();
        DataSource fds = new FileDataSource("D:\\wxc\\RpaDemo01\\src\\main\\resources\\imgs\\bsgm.jpg"); // 图片文件路径
        imagePart.setDataHandler(new DataHandler(fds));
        imagePart.setHeader("Content-ID", "<image1>"); // 设置 Content-ID，用于在 HTML 中引用

        // 将 HTML 部分和图片部分添加到邮件中
        multipart.addBodyPart(htmlPart);
        multipart.addBodyPart(imagePart);

        // 设置邮件内容
        message.setContent(multipart);

        // 发送邮件
for (int i=0;i<10;i++) {
    Transport.send(message);
    System.out.println(i+"Email sent successfully!");
}
    }
}
